import React, { useEffect, useRef, useState } from 'react';
import listPlugin from '@fullcalendar/list';
import FullCalendar from '@fullcalendar/react';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import interactionPlugin from '@fullcalendar/interaction';
import { useClassDetail } from '@/views/attendance/classInfo/hooks/useClassDetail';
import dayjs from 'dayjs';
import { findByStaffId } from '@/views/attendance/classInfo/api';
import { getUserInfo } from '@/utils/storage';
import WorkDetail from './detail';

const WorkCalendar = () => {
    const calendarRef = useRef(null);
    // 日历事件
    const [calendarEvents, setCalendarEvents] = useState([]);

    // 右侧排班详情区域展示
    const detail = useClassDetail({
        // callback: refreshCalendarEvents,
    });

    // 日历顶部工具栏
    const headerTools = {
        left: 'prev,next today',
        center: 'title',
        right: 'dayGridMonth'
    };

    // 日历工具栏汉化展示
    const headerToolText = {
        today: '今天',
        month: '月',
    }

    // 日历视图
    const calendarViews = {
        timeGridWeek: {
            allDaySlot: false,
            // slotDuration: '00:15',
            // slotLabelInterval: '00:30',
            slotLabelFormat: {
                hour: '2-digit',
                minute: '2-digit',
            },
        },
        timeGridDay: {
            allDaySlot: false,
            // slotDuration: '00:15',
            slotLabelFormat: {
                hour: '2-digit',
                minute: '2-digit',
            },
        },
    };

    const handleEventClick = (info) => {
        info.jsEvent.preventDefault(); // 阻止默认行为
        let event = calendarEvents.find(item => item.id === info.event.id);
        detail.setDate(event.date);
        detail.setEvents(calendarEvents.filter(item => item.date === event.date));
    };

    // 日期点击事件
    const calendarDateClickHandle = (info) => {
        info.jsEvent.preventDefault(); // 阻止默认行为

        // 重置detail组件
        let currentDate = dayjs(info.date).format('YYYY-MM-DD');
        detail.setDate(currentDate);
        let events = calendarEvents.filter(item => item.date === currentDate);
        detail.setEvents(events);
    }

    /**
         * 刷新日历视图
         * 
         * 相关文档[https://fullcalendar.io/docs/view-object]
         */
    const refreshCalendarEvents = (date = undefined) => {
        if (!calendarRef.current) {
            return;
        }
        date = date || dayjs().format('YYYY-MM-DD');

        const calendarView = calendarRef.current?.getApi().view;
        let data = {
            startDate: dayjs(calendarView.activeStart).format('YYYY-MM-DD'),
            endDate: dayjs(calendarView.activeEnd).add(-1, 'd').format('YYYY-MM-DD'),
        };

        let userInfo = getUserInfo();
        let query = {
            id: userInfo?.staffId,
            data,
        }

        findByStaffId(query).then(resp => {
            // 全部事件
            let events = [];
            // 排班明细事件
            let selectedEvents = [];
            resp?.data?.forEach((each) => {
                let detail = {
                    id: each.id,
                    date: each.workDate,
                    staffs: each.staffs,
                    beginTime: dayjs(each.startTime, 'HH:mm:ss').format('HH:mm'),
                    finishTime: dayjs(each.endTime, 'HH:mm:ss').format('HH:mm'),
                    title: each.name,
                    start: each.workDate + ' ' + each.startTime,
                    end: each.workDate + ' ' + each.endTime,
                    // textColor: '#000',
                    backgroundColor: each.color,
                    borderColor: each.color,
                    editable: false,
                };
                events.push(detail);
                if (each.workDate === date) {
                    selectedEvents.push(detail);
                }
            });
            setCalendarEvents(events);
            // 初始化detail组件
            detail.setDate(date);
            detail.setSelectedEvent(null);
            detail.setEvents(selectedEvents);
        });
    }

    useEffect(() => {
        refreshCalendarEvents();
    }, []);

    return (
        <div style={{ padding: 12, display: 'flex', gap: 20, height: 'calc(100vh - 146px)' }}>
            {/* 左侧日历区域 */}
            <div style={{ width: 700, overflow: 'hidden' }}>
                <FullCalendar
                    ref={calendarRef}
                    height={'calc(100vh - 172px)'}
                    locale="zh-cn"
                    eventColor="#4285f4"
                    headerToolbar={headerTools}
                    buttonText={headerToolText}
                    dayHeaderFormat={{ weekday: 'short' }}
                    views={calendarViews}
                    // navLinks={true}
                    editable={true}
                    firstDay={0}
                    plugins={[dayGridPlugin, timeGridPlugin, listPlugin, interactionPlugin]}
                    initialView="dayGridMonth"
                    dateClick={calendarDateClickHandle}
                    eventClick={handleEventClick}
                    events={calendarEvents}
                    selectable={true}
                />
            </div>

            {/* 右侧事件详情区域 */}
            <WorkDetail props={detail} />
        </div>
    );
}

export default WorkCalendar;